import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferencesUtils {
  static late SharedPreferences _sharedPreferences;
  
  ///异步初始化 初始化也就 0.2秒
  static init() async {
    DateTime dateTime= DateTime.now();
    print("111"+dateTime.toString());
    _sharedPreferences = await SharedPreferences.getInstance();
    print("222"+DateTime.now().toString());
  }

  /// 存数据
  static void savePreference(String key, Object value)  {
    if (value is int) {
       _sharedPreferences.setInt(key, value);
    } else if (value is double) {
       _sharedPreferences.setDouble(key, value);
    } else if (value is bool) {
       _sharedPreferences.setBool(key, value);
    } else if (value is String) {
       _sharedPreferences.setString(key, value);
    } else if (value is List<String>) {
       _sharedPreferences.setStringList(key, value);
    } else {
      throw Exception("不能得到这种类型");
    }
  }

  /// 取数据
  static Future getPreference(String key, Object defaultValue) async {
    if (defaultValue is int) {
      return _sharedPreferences.getInt(key);
    } else if (defaultValue is double) {
      return _sharedPreferences.getDouble(key);
    } else if (defaultValue is bool) {
      return _sharedPreferences.getBool(key);
    } else if (defaultValue is String) {
      return _sharedPreferences.getString(key);
    } else if (defaultValue is List) {
      return _sharedPreferences.getStringList(key);
    } else {
      throw Exception("不能得到这种类型");
    }
  }

  /// 删除指定数据
  static void remove(String key)  {
    _sharedPreferences.remove(key); //删除指定键
  }

  ///清空整个缓存
  static void clear()  {
    _sharedPreferences.clear(); ////清空缓存
  }
}
